package com.fjec.market.rabbitmq.provider;

import com.fjec.common.protocol.FjecFruitsProto;
import com.fjec.common.util.SequenceIdGenerator;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class SysMsgProvider {

    @Value("${fjec.market.sysmsg.exchange.name}")
    private String exchangeName;

    @Value("${fjec.market.sysmsg.router.key}")
    private String routingKey;

    @Resource(name = "sysMessageAmqpTemplate")
    private RabbitTemplate sysMessageAmqpTemplate;

    @Autowired
    private SequenceIdGenerator sequenceIdGenerator;

    public void sendSysMessage(Integer msgType, Integer bizType, Map<String, String> bizData,
                               Long userId, String title, String content, Long delay) {
        Long msgId = sequenceIdGenerator.nextId();
        FjecFruitsProto.SysMsg sysMsg = FjecFruitsProto.SysMsg
                .newBuilder()
                .setMsgId(msgId)
                .setMsgType(msgType)
                .setBizType(bizType)
                .putAllBizData(bizData)
                .setUserId(userId)
                .setTitle(title)
                .setContent(content)
                .setDelay(delay)
                .build();
        FjecFruitsProto.FjecFruitsMsg msg = FjecFruitsProto.FjecFruitsMsg.newBuilder()
                .setSysMsg(sysMsg)
                .build();
        MessageProperties props = new MessageProperties();
        if (delay > 0)
            props.setHeader("delay", delay * 1000);
        Message message = new Message(msg.toByteArray(), props);
        sysMessageAmqpTemplate.convertAndSend(exchangeName, routingKey, message);
    }

}
